package com.hkts.sinoiov.sinoiovRecord.service.serviceimpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hkts.management.common.utils.*;
import com.hkts.management.common.vo.UserBasicInfoVo;
import com.hkts.sinoiov.async.AsyncServiceImpl;
import com.hkts.sinoiov.feign.FeignInterface;
import com.hkts.sinoiov.model.ApiHisTrack;
import com.hkts.sinoiov.model.ApiLocation;
import com.hkts.sinoiov.openapi.OpenApi;
import com.hkts.sinoiov.sinoiovHisTrack.entity.SinoiovHisTrack;
import com.hkts.sinoiov.sinoiovHisTrack.service.ISinoiovHisTrackService;
import com.hkts.sinoiov.sinoiovLocation.entity.SinoiovLocation;
import com.hkts.sinoiov.sinoiovLocation.service.ISinoiovLocationService;
import com.hkts.sinoiov.sinoiovRecord.entity.SinoiovRecord;
import com.hkts.sinoiov.sinoiovRecord.mapper.SinoiovRecordMapper;
import com.hkts.sinoiov.sinoiovRecord.service.ISinoiovRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hkts.sinoiov.utils.Douglas;
import com.hkts.sinoiov.utils.GPSUtil;
import com.hkts.sinoiov.utils.ResultOpen;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hml
 * @since 2021-08-11
 */
@Service
@Transactional
@Slf4j
public class SinoiovRecordServiceImpl extends ServiceImpl<SinoiovRecordMapper, SinoiovRecord> implements ISinoiovRecordService {


    @Autowired
    private SinoiovRecordMapper sinoiovRecordMapper;
    @Autowired
    private OpenApi openApi;
    @Autowired
    private ISinoiovLocationService locationService;
    @Autowired
    private AsyncServiceImpl asyncService;
    @Autowired
    private FeignInterface feignInterface;

    @Override
    public IPage<SinoiovRecord> selectPage(Page<SinoiovRecord> page, SinoiovRecord sinoiovRecord) {
        QueryWrapper<SinoiovRecord> query = Wrappers.query();
        return sinoiovRecordMapper.selectPage(page, query);
    }

    @Override
    public Result<Object> vLastLocationV3(String vclN) {
        try {
            if(vclN==null){
                return ResultUtil.error("参数不正确");
            }
            Result<UserBasicInfoVo> userBasicInfoVoResult= feignInterface.remoteUserBasicInfo();
            if(!userBasicInfoVoResult.isSuccess()){
                return ResultUtil.error("调取用户信息失败");
            }
            ResultOpen<Object>  resultOpen=  openApi.vLastLocationV3(vclN);
            if(resultOpen.getStatus()==1001&&resultOpen.getResult()!=null){
                SinoiovRecord sinoiovRecord=new SinoiovRecord();
                String recordId=String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId());
                sinoiovRecord.setId(recordId);
                sinoiovRecord.setCarrierPalte(vclN);
                sinoiovRecord.setSinoiovCode(SinoiovRecord.LOCATIONV3);
                ApiLocation apiLocation= JSON.parseObject(resultOpen.getResult().toString(),ApiLocation.class);
                double[] coordinates= GPSUtil.coordinatesStrToDou(apiLocation.getLat(),apiLocation.getLon());

                SinoiovLocation sinoiovLocation= BeanConvertUtils.copy(apiLocation,SinoiovLocation.class,"lat","lon","utc");
                sinoiovLocation.setId(String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId()));
                sinoiovLocation.setRecordId(recordId);
                sinoiovLocation.setAdr(apiLocation.getAdr());
                sinoiovLocation.setLat(BigDecimal.valueOf(coordinates[0]));
                sinoiovLocation.setLon(BigDecimal.valueOf(coordinates[1]));
                sinoiovLocation.setUtc(DateUtils.timestampToLocalDateTime(Long.parseLong(apiLocation.getUtc())));
                log.info("坐标{}",coordinates);
                locationService.save(sinoiovLocation);
                sinoiovRecordMapper.insert(sinoiovRecord);
                return  ResultUtil.data(sinoiovLocation);
            }else {
                assert resultOpen.getResult() != null;
                return ResultUtil.error(resultOpen.getResult().toString());
            }
        }catch (Exception e){
            return ResultUtil.error("服务异常");
        }

    }

    @Override
    public Result<Object> vHisTrack24(String vclN, LocalDateTime qryBtm, long hours) {
            try {
                Result<UserBasicInfoVo> userBasicInfoVoResult= feignInterface.remoteUserBasicInfo();
                if(!userBasicInfoVoResult.isSuccess()){
                    return ResultUtil.error("调取用户信息失败");
                }
                ResultOpen<Object> resultOpen=  openApi.vHisTrack24(vclN,qryBtm,hours);
                if(resultOpen.getStatus()==1001){
                    if(resultOpen.getResult()!=null){
                        SinoiovRecord sinoiovRecord=new SinoiovRecord();
                        String recordId=String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId());
                        sinoiovRecord.setId(recordId);
                        sinoiovRecord.setCarrierPalte(vclN);
                        sinoiovRecord.setSinoiovCode(SinoiovRecord.LOCATIONV3);
                        sinoiovRecord.setCreator(userBasicInfoVoResult.getResult().getId());
                        List<ApiHisTrack> sowDetailDtos = JSONArray.parseArray(resultOpen.getResult().toString(), ApiHisTrack.class);
                        List<SinoiovHisTrack> sinoiovHisTracks=sowDetailDtos.stream().map(t->openApi.apiCoverSiniov(t,recordId)).collect(Collectors.toList());
                        sinoiovRecordMapper.insert(sinoiovRecord);
    //                    hisTrackService.saveBatch(sinoiovHisTracks);
                        asyncService.saveBatchHisTrack(sinoiovHisTracks);
                        if(sinoiovHisTracks.size()>20){
                            List<SinoiovHisTrack> result= Douglas.douglasData(sinoiovHisTracks);
                            log.info("抽稀前{},抽稀后{}",sinoiovHisTracks.size(),result.size());
                             return ResultUtil.data(result);
                        }else {
                             return ResultUtil.data(sinoiovHisTracks);

                        }
                    }else {
                        return ResultUtil.data(resultOpen.getResult());
                    }
                }else {
                    String result=resultOpen.getStatus().toString()+"--"+resultOpen.getResult();
                    return ResultUtil.error(result);
                }

            }catch (Exception e){
                log.error(String.valueOf(e));
                return ResultUtil.error("服务异常");
            }
    }
}
